function out = my_accumarray(TC_idx,x)
%sum values of x within the same value of groupid TC_idx
%i.e. sum_i x_{ij} within each group j
% STATA equivalent: by tc: egen out=total(x). Here, x can be matrix nxK
%K is the number of variables in x; n=dimension(tc)
%However, TC_idx is not TC (categorical var). TC_idx is obs index of TC and
%TC_idx is a cell with dimension=number of categories of TC
l=length(TC_idx); %number of groups
[n,k,m]=size(x); out=NaN(n,k,m); 
%caveat! always specify the dimension of sum, along row=1, if missing the
%dimension, MATLAB automatically sum all rows if there is a matrix RxN
%if the matrix is 1 x N, then the sum is sum of that vector, sum all cols
if m==1
for i=1:l, v=TC_idx{i}; out(v,:)=repmat(sum(x(v,:),1),[length(v) 1]); end
end
if m>1
for i=1:l, v=TC_idx{i}; out(v,:,:)=repmat(sum(x(v,:,:),1),[length(v) 1]); end
end

end